package com.xiaoq.user.endpoint;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tls.sigcheck.tls_sigcheck;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping(value = "/api/v1/sig")
@Api(tags={"用户签名Sig相关Api"})
public class TencentSigEndpoint {
	
	private static final String SdkAppid = "1400092469";
	
	@Value("${tencent.jni}")
	private String jni;
	
	private static final class SigDataResponse extends GenericDataResponse<String> {}
	
	private static final Logger LOG = LoggerFactory.getLogger(TencentSigEndpoint.class);
	
	@ApiOperation(value = "获取加密签名Sig", notes = "获取加密签名Sig")
	@ApiResponses({ @ApiResponse(code = 200, message = "获取加密签名Sig", response = SigDataResponse.class)})
	@GetMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> getSig(HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		tls_sigcheck tls = new tls_sigcheck();
		tls.loadJniLib(jni);
		StringBuilder strBuilder = new StringBuilder();
		String s = "";

		BufferedReader br = null;
		InputStream in = null;
		InputStreamReader read = null;
		try {
			in = getClass().getClassLoader().getResourceAsStream("ec_key.pem");
			read = new InputStreamReader(in);
			br = new BufferedReader(read);
			while ((s = br.readLine()) != null) {
	            strBuilder.append(s + '\n');
	        }
			String priKey = strBuilder.toString();
			int ret = tls.tls_gen_signature_ex2(SdkAppid, userId, priKey);
			while ((s = br.readLine()) != null) {
			    strBuilder.append(s + '\n');
			}
			if (0 != ret) {
				return GenericResponse.ng(tls.getErrMsg());
	        }else{
	        	return SigDataResponse.okWithData(tls.getSig());
	        }  
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return GenericResponse.ng("网络异常！");
       
	}
	
	@ApiOperation(value = "检验Sig", notes = "检验Sig")
	@ApiResponses({ @ApiResponse(code = 200, message = "检验Sig", response = SigDataResponse.class)})
	@GetMapping(value = "/ver", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> verSig(String sig,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		tls_sigcheck tls = new tls_sigcheck();
		tls.loadJniLib(jni);
		StringBuilder strBuilder = new StringBuilder();
		String s = "";

		BufferedReader br = null;
		InputStream in = null;
		InputStreamReader read = null;
		try {
			in = getClass().getClassLoader().getResourceAsStream("public.pem");
			read = new InputStreamReader(in);
			br = new BufferedReader(read);
			while ((s = br.readLine()) != null) {
	            strBuilder.append(s + '\n');
	        }
			String pubKey = strBuilder.toString();
			int ret = tls.tls_check_signature_ex2(sig, pubKey, SdkAppid, userId);
			while ((s = br.readLine()) != null) {
			    strBuilder.append(s + '\n');
			}
			if (0 != ret) {
				return GenericResponse.ng("校验失败！");
	        }else{
	        	return GenericResponse.ok();
	        }  
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return GenericResponse.ng("网络异常！");
       
	}
	

}
